package com.coocaa.coolink_tvos_mobile_demo.ui.home;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.coocaa.coolink_tvos_mobile_demo.databinding.FragmentHomeBinding;
import com.coocaa.coolink_tvos_mobile_demo.ui.dashboard.DashboardFragment;
import com.coocaa.coolink_tvos_mobile_demo.ui.recyclelist.ItemAdapter;
import com.coocaa.coolink_tvos_mobile_demo.utils.FileUtils;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private ItemAdapter itemAdapter;
    private IRemoteItemSelected listener;

    private final ActivityResultLauncher<String> mGetContent =
            registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> {
                if (uri != null) {
                    String path = FileUtils.getPath(getActivity(), uri);
                    final TextView tvFilePathView = binding.tvFilePath;
                    Log.d(getClass().getSimpleName(),"path = "+path );
                    tvFilePathView.setText(path);
                }
            });

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listener = (HomeFragment.IRemoteItemSelected) getActivity();

    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        final TextView tvFilePathView = binding.tvFilePath;
        homeViewModel.getFilePathText().observe(getViewLifecycleOwner(), tvFilePathView::setText);

        final TextView stateHintView = binding.stateHint;
        homeViewModel.getConnectedStateText().observe(getViewLifecycleOwner(),stateHintView::setText);

        final Button selectFileBtn = binding.btnSelectFile;
        selectFileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mGetContent.launch("image/*,video/*");
            }
        });

        // 获取ScrollView控件对象
        final ScrollView scrollView = binding.listScroll;

// 获取RelativeLayout控件对象
        final RelativeLayout relativeLayout = binding.relativeLayout;

// 获取RecyclerView控件对象
        final RecyclerView recyclerView = binding.savedList;
// 添加或删除RecyclerView中的item时，动态计算ScrollView的高度
        recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                int recyclerViewHeight = recyclerView.getHeight();
                int scrollViewMaxHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, getResources().getDisplayMetrics());

                // 如果RecyclerView的高度小于等于ScrollView的最大高度，则将ScrollView的高度设置为RecyclerView的高度
                if (recyclerViewHeight <= scrollViewMaxHeight) {
                    scrollView.getLayoutParams().height = recyclerViewHeight;
                    scrollView.requestLayout();
                }
                // 如果RecyclerView的高度大于ScrollView的最大高度，则将ScrollView的高度设置为最大高度
                else {
                    scrollView.getLayoutParams().height = scrollViewMaxHeight;
                    scrollView.requestLayout();
                }
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        itemAdapter = new ItemAdapter(homeViewModel.getSavedListIem(),getViewLifecycleOwner());
        recyclerView.setAdapter(itemAdapter);
        itemAdapter.setItemSelectedListener(homeViewModel);
        int scrollViewMaxHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, getResources().getDisplayMetrics());

        final EditText nickNameText = binding.nickName;
        final EditText coolinkIDText = binding.coolinkID;
        homeViewModel.getNickNameText().observe(getViewLifecycleOwner(), nickNameText::setText);
        homeViewModel.getClientIDText().observe(getViewLifecycleOwner(), coolinkIDText::setText);
        nickNameText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                homeViewModel.setNickNameText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        coolinkIDText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                homeViewModel.setCoolinkIDText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        final Button savedBtn = binding.buttonSave;
        final Button connectBtn = binding.buttonConnect;

        savedBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                homeViewModel.setSaveBtnClicked();
            }
        });

        connectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                homeViewModel.setConnectBtnClicked();
                final EditText coolinkIDText = binding.coolinkID;
                listener.setCurrentRemoteID(coolinkIDText.getText().toString());
            }
        });
        return root;
    }

    public String getConnetedItem(){
        if ( binding!=null ){
            return binding.coolinkID.getText().toString();
        }
        return null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    public interface IRemoteItemSelected {
        void setCurrentRemoteID(String remoteID);
    }
}